import { defineStore } from "pinia";

export const useUserStore = defineStore('user' , {
    state: () => ({
        token: null,        // 用户token
        rememberMe: false   // 是否记住我
    }),
    actions: {
        login(token) {
            this.token = token

            if(this.rememberMe) {
                localStorage.setItem('token', token)
                localStorage.setItem('rememberMe', 'true')
            } else {
                localStorage.removeItem('token')
                localStorage.removeItem('rememberMe')
            }
        },
        logout() {
            this.token = null
            localStorage.removeItem('token')
            localStorage.removeItem('rememberMe')
        },
        // 初始化用户状态（从 LocalStorage 中恢复）
        initialize() {
            const token = localStorage.getItem('token');
            const rememberMe = localStorage.getItem('rememberMe');

            if (token && rememberMe === 'true') {
                this.token = token;
                this.rememberMe = true;
            }
        },
        // 设置“记住我”状态
        setRememberMe(value) {
            this.rememberMe = value;
        },
    },
    getters: {
        currentToken: (state) => state.token
    }
})